// src/pages/ForexSpot/ForexSpot.jsx

import React, { useEffect, useState } from 'react';
import {
  Table,
  Card,
  Input,
  Spin,
  message,
  Modal,
  Form,
  InputNumber,
  Button,
  Tag,
  Tooltip,
  Badge,
} from 'antd';
import { useNavigate } from 'react-router-dom';
import {
  $fetchSpotForexList,
  $buyForex,
  $sellForex,
} from '../../api/forexApi'; // 请根据实际项目路径调整
import dayjs from 'dayjs';

import {
  ArrowUpOutlined,
  SearchOutlined,
  ShoppingCartOutlined,
  DollarOutlined,
  DollarCircleOutlined,
  RiseOutlined,
  FallOutlined,
} from '@ant-design/icons';

import './ForexSpot.scss';

const { Search } = Input;

/**
 * 从 localStorage 获取用户 ID
 */
const getUserId = () => {
  const userInfo = localStorage.getItem('user_info');
  if (!userInfo) throw { msg: '用户未登录或未找到用户信息' };
  try {
    return JSON.parse(userInfo).id;
  } catch {
    throw { msg: '用户信息解析失败' };
  }
};

const ForexSpot = () => {
  const [rawData, setRawData] = useState([]);
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);

  const [isBuyModalVisible, setIsBuyModalVisible] = useState(false);
  const [isSellModalVisible, setIsSellModalVisible] = useState(false);
  const [selectedForex, setSelectedForex] = useState(null);

  const navigate = useNavigate();

  // 1. 页面挂载时拉取外汇列表
  useEffect(() => {
    setLoading(true);
    $fetchSpotForexList()
      .then((list) => {
        const formatted = list.map((item, idx) => ({
          index: idx + 1,
          code: item.code,
          name: item.name,
          latest: item.latest_price,
          change: item.change_amount,
          open: item.open,
          high: item.high,
          low: item.low,
          previous: item.previous_close,
          changePercent: item.change_percent, // 假设后台提供涨跌幅
        }));
        setRawData(formatted);
        setData(formatted);
      })
      .catch((err) => {
        console.error(err);
        message.error(`获取外汇列表失败：${err.message || err.msg}`);
      })
      .finally(() => setLoading(false));
  }, []);

  // 2. 搜索
  const handleSearch = (value) => {
    const txt = value.trim().toLowerCase();
    setData(
      txt
        ? rawData.filter(
            (item) =>
              item.code.toLowerCase().includes(txt) ||
              item.name.toLowerCase().includes(txt)
          )
        : rawData
    );
  };

  // 3. 打开购买弹窗
  const handleBuyForex = (forex) => {
    setSelectedForex(forex);
    setIsBuyModalVisible(true);
  };

  // 4. 打开卖出弹窗
  const handleSellForex = (forex) => {
    setSelectedForex(forex);
    setIsSellModalVisible(true);
  };

  // 5. 提交购买
  const handleBuySubmit = async (values) => {
    try {
      const userid = getUserId();
      await $buyForex({
        userid: parseInt(userid, 10),
        products_id: selectedForex.code,
        products_name: selectedForex.name,
        quantity: values.quantity,
        price: selectedForex.latest,
        trade_time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      });
      message.success('购买成功');
      setIsBuyModalVisible(false);
    } catch (err) {
      console.error(err);
      message.error(err.msg || '购买失败');
    }
  };

  // 6. 提交卖出
  const handleSellSubmit = async (values) => {
    try {
      const userid = getUserId();
      await $sellForex({
        userid: parseInt(userid, 10),
        products_id: selectedForex.code,
        products_name: selectedForex.name,
        quantity: values.quantity,
        price: selectedForex.latest,
        trade_time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      });
      message.success('卖出成功');
      setIsSellModalVisible(false);
    } catch (err) {
      console.error(err);
      message.error(err.msg || '卖出失败');
    }
  };

  // 7. 渲染“涨跌额/涨跌幅”标签
  const renderChangeTag = (change, changePercent) => {
    const amt = parseFloat(change);
    const pct = parseFloat(changePercent);
    if (pct > 0) {
      return (
        <Tag color="red" className="change-tag positive">
          <RiseOutlined /> {pct.toFixed(2)}%
        </Tag>
      );
    } else if (pct < 0) {
      return (
        <Tag color="green" className="change-tag negative">
          <FallOutlined /> {Math.abs(pct).toFixed(2)}%
        </Tag>
      );
    } else {
      return <Tag color="default" className="change-tag neutral">0.00%</Tag>;
    }
  };

  // 8. 渲染“最新价”颜色
  const renderLatest = (latest, changePercent) => {
    const pct = parseFloat(changePercent);
    const className =
      pct > 0 ? 'positive-text' : pct < 0 ? 'negative-text' : 'neutral-text';
    return (
      <span className={`price-text ${className}`}>¥{Number(latest).toFixed(4)}</span>
    );
  };

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 60,
      render: (_, __, idx) => <div className="index-cell">{idx + 1}</div>,
    },
    {
      title: '外汇信息',
      key: 'forexInfo',
      width: 200,
      render: (_, record) => (
        <div className="forex-info-cell">
          <div className="forex-code">
            <a
              onClick={() => navigate(`/forex/trend?symbol=${record.code}`)}
              className="code-link"
            >
              {record.code}
            </a>
          </div>
          <div className="forex-name">{record.name}</div>
        </div>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      render: (_, record) => (
        <div className="action-buttons">
          <Button
            type="primary"
            size="small"
            icon={<ShoppingCartOutlined />}
            onClick={() => handleBuyForex(record)}
            className="buy-button"
          >
            买入
          </Button>
          <Button
            danger
            size="small"
            icon={<DollarOutlined />}
            onClick={() => handleSellForex(record)}
            className="sell-button"
          >
            卖出
          </Button>
        </div>
      ),
    },
    {
      title: '最新价',
      dataIndex: 'latest',
      key: 'latest',
      width: 120,
      render: (val, record) => renderLatest(val, record.changePercent),
    },
    {
      title: '涨跌额',
      dataIndex: 'change',
      key: 'change',
      width: 100,
      render: (val) => {
        const amt = parseFloat(val);
        const className = amt > 0 ? 'positive-text' : amt < 0 ? 'negative-text' : 'neutral-text';
        return <span className={className}>{val}</span>;
      },
    },
    {
      title: '涨跌幅',
      dataIndex: 'changePercent',
      key: 'changePercent',
      width: 100,
      render: (val, record) => renderChangeTag(record.change, val),
    },
    {
      title: '开盘价',
      dataIndex: 'open',
      key: 'open',
      width: 120,
      render: (val) => <span className="neutral-text">¥{val}</span>,
    },
    {
      title: '最高价',
      dataIndex: 'high',
      key: 'high',
      width: 120,
      render: (val) => <span className="high-price">¥{val}</span>,
    },
    {
      title: '最低价',
      dataIndex: 'low',
      key: 'low',
      width: 120,
      render: (val) => <span className="low-price">¥{val}</span>,
    },
    {
      title: '昨收价',
      dataIndex: 'previous',
      key: 'previous',
      width: 120,
      render: (val) => <span className="neutral-text">¥{val}</span>,
    },
  ];

  return (
    <div className="forex-spot-page">
      <div className="page-header">
        <div className="header-content">
          <div className="header-title">
            <DollarCircleOutlined className="header-icon" />
            <h1>外汇当期列表</h1>
            <Badge count={data.length} className="stock-count-badge" />
          </div>
          <div className="market-stats">
            <div className="stat-item">
              <ArrowUpOutlined />
              <span>实时更新</span>
            </div>
          </div>
        </div>
      </div>

      <Card className="stock-card" bordered={false}>
        <div className="search-section">
          <Search
            placeholder="输入外汇代码或名称..."
            allowClear
            enterButton={<SearchOutlined />}
            onSearch={handleSearch}
            className="stock-search"
            size="large"
          />
        </div>

        {loading ? (
          <div className="loading-container">
            <Spin size="large" tip="正在加载外汇数据..." />
          </div>
        ) : (
          <div className="table-container">
            <Table
              rowKey="index"
              dataSource={data}
              columns={columns}
              pagination={{
                pageSize: 20,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) =>
                  `共 ${total} 条记录，显示第 ${range[0]}-${range[1]} 条`,
              }}
              scroll={{ x: 'max-content', y: 600 }}
              className="stock-table"
              rowClassName={(record) => {
                const pct = parseFloat(record.changePercent);
                if (pct > 0) return 'positive-row';
                if (pct < 0) return 'negative-row';
                return 'neutral-row';
              }}
            />
          </div>
        )}
      </Card>

      {/* 购买弹窗 */}
      <Modal
        title={
          <div className="modal-title">
            <ShoppingCartOutlined />
            <span>购买外汇</span>
          </div>
        }
        visible={isBuyModalVisible}
        onCancel={() => setIsBuyModalVisible(false)}
        footer={null}
        className="trade-modal buy-modal"
      >
        {selectedForex && (
          <div className="stock-info-modal">
            <div className="selected-stock">
              <div className="stock-code">{selectedForex.code}</div>
              <div className="stock-name-modal">{selectedForex.name}</div>
              <div className="current-price">
                当前价: ¥{Number(selectedForex.latest).toFixed(4)}
              </div>
            </div>
          </div>
        )}
        <Form onFinish={handleBuySubmit} layout="vertical" className="trade-form">
          <Form.Item
            label="购买数量 (单位)"
            name="quantity"
            rules={[{ required: true, message: '请输入购买数量' }]}
          >
            <InputNumber
              min={1}
              style={{ width: '100%' }}
              placeholder="请输入购买单位"
            />
          </Form.Item>
          <Form.Item className="modal-buttons">
            <Button
              type="primary"
              htmlType="submit"
              size="large"
              icon={<ShoppingCartOutlined />}
              className="confirm-buy-btn"
            >
              确认购买
            </Button>
          </Form.Item>
        </Form>
      </Modal>

      {/* 卖出弹窗 */}
      <Modal
        title={
          <div className="modal-title">
            <DollarOutlined />
            <span>卖出外汇</span>
          </div>
        }
        visible={isSellModalVisible}
        onCancel={() => setIsSellModalVisible(false)}
        footer={null}
        className="trade-modal sell-modal"
      >
        {selectedForex && (
          <div className="stock-info-modal">
            <div className="selected-stock">
              <div className="stock-code">{selectedForex.code}</div>
              <div className="stock-name-modal">{selectedForex.name}</div>
              <div className="current-price">
                当前价: ¥{Number(selectedForex.latest).toFixed(4)}
              </div>
            </div>
          </div>
        )}
        <Form onFinish={handleSellSubmit} layout="vertical" className="trade-form">
          <Form.Item
            label="卖出数量 (单位)"
            name="quantity"
            rules={[{ required: true, message: '请输入卖出数量' }]}
          >
            <InputNumber
              min={1}
              style={{ width: '100%' }}
              placeholder="请输入卖出单位"
            />
          </Form.Item>
          <Form.Item className="modal-buttons">
            <Button
              danger
              htmlType="submit"
              size="large"
              icon={<DollarOutlined />}
              className="confirm-sell-btn"
            >
              确认卖出
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ForexSpot;
